/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package com.example.cryptodemo.aes;

/**
 * XMLParse class
 * <p>
 * 提供提取消息格式中的密文及生成回复消息格式的接口.
 */
public class JSONParser implements Parser {
    /**
     * 生成JSON消息
     *
     * @param encrypt   加密后的消息密文
     * @param signature 安全签名
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @return 生成的JSON字符串
     */
    @Override
    public <T> String generate(Message<T> message) {
        switch (message.getEncryptType()) {
            case 0: {
                String format = "{" +
                        "\"nonce\":\"%4$s\"," +
                        "\"signature\":\"%2$s\"," +
                        "\"data\":\"%1$s\"," +
                        "\"timeStamp\":\"%3$s\"}";
                return String.format(format,message.getData().toString(),
                        message.getSignature(), message.getTimeStamp(), message.getNonce()
                        );
            }
            case 1: {
                String format = "{\"encryptData\":\"%1$s\"," +
                        "\"nonce\":\"%4$s\"," +
                        "\"signature\":\"%2$s\"," +
                        "\"data\":\"%5$s\"," +
                        "\"timeStamp\":\"%3$s\"}";
                return String.format(format, message.getEncryptedData(),
                        message.getSignature(), message.getTimeStamp(), message.getNonce(),
                        message.getData().toString());
            }
            case 2: {
                String format = "{\"encryptData\":\"%1$s\"," +
                        "\"nonce\":\"%4$s\"," +
                        "\"signature\":\"%2$s\"," +
                        "\"timeStamp\":\"%3$s\"}";
                return String.format(format, message.getEncryptedData(),
                        message.getSignature(), message.getTimeStamp(), message.getNonce());
            }
            default:
                return null;
        }
    }
}
